/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { ControlVO } from '@ibiz-template/runtime';
import { chunk } from 'lodash-es';
import { GridController, GridRowState } from '../../../controller';

/**
 * 使用分页组件
 *
 * @export
 * @param {GridController} c
 * @return {*}  {{
 *   onPageChange: (page: number) => void;
 *   onPageSizeChange: (size: number) => void;
 *   onPageRefresh: () => void;
 * }}
 */
export function usePagination(c: GridController): {
  onPageChange: (page: number) => void;
  onPageSizeChange: (size: number) => void;
  onPageRefresh: () => void;
} {
  // 初始化表格项
  const initGridItems = () => {
    if (Array.isArray(c.state.simpleData)) {
      c.state.items =
        chunk(c.state.simpleData, c.state.size)[c.state.curPage - 1] || [];
      c.state.rows = c.state.items.map(item => {
        const row = new GridRowState(new ControlVO(item), c);
        return row;
      });
    }
  };

  function onPageChange(page: number): void {
    if (!page || page === c.state.curPage) {
      return;
    }
    c.state.curPage = page;
    if (c.runMode === 'DESIGN') {
      initGridItems();
      return;
    }
    c.load();
  }

  function onPageSizeChange(size: number): void {
    if (!size || size === c.state.size) {
      return;
    }
    c.state.size = size;
    if (c.runMode === 'DESIGN') {
      initGridItems();
      return;
    }
    // 当page为第一页的时候切换size不会触发pageChange，需要自己触发加载
    if (c.state.curPage !== 1) {
      c.state.curPage = 1;
    }
    c.load();
  }

  function onPageRefresh(): void {
    c.load();
  }
  return { onPageChange, onPageSizeChange, onPageRefresh };
}
